package cn.saltybe.analysis.scheduler;

import cn.saltybe.analysis.analyze.PageViewAnalyze;
import cn.saltybe.analysis.analyze.UserViewAnalyze;
import cn.saltybe.analysis.entity.result.PageView;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@Configuration
@EnableScheduling
public class ViewLogScheduler {
    @Scheduled(cron = "0 0 0 * * ?")
    private void configureTask() {
        Date date = new Date();
        Calendar calendar = setCalendar(date.getYear(), date.getMonth() + 1, date.getDate());
        calendar = getBeforeDay(calendar);
        date = new Date(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE));
        System.out.println("执行定时任务：分析前一日(" + new SimpleDateFormat("yyyy-MM-dd").format(date) + ")网站页面PV");
        try {
            PageViewAnalyze.analyze(date);
            PageViewAnalyze.exportData(date);
            System.out.println("分析前一日网站页面PV完成。");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("分析前一日网站页面PV失败。");
        }

        System.out.println("执行定时任务：分析前一日(" + new SimpleDateFormat("yyyy-MM-dd").format(date) + ")网站UV");
        try {
            UserViewAnalyze.analyze(date);
            UserViewAnalyze.exportData(date);
            System.out.println("分析前一日网站UV完成。");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("分析前一日网站UV失败。");
        }
    }

    public static Calendar setCalendar(int year, int month, int date) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, date);
        return calendar;
    }

    private static Calendar getBeforeDay(Calendar calendar) {
        int day = calendar.get(Calendar.DATE);
        calendar.set(Calendar.DATE, day - 1);
        return calendar;
    }
}
